const token_key = "abcdefg"
exports.token_key = token_key

const {reservation,UserInfo,productService,sequelize,User} = require('../../dbConfig/index.js')
const { Op } = require('sequelize')

const addReservation = async (ctx,next)=>{
	const body = ctx.request.body
	// 先查产品详情  再查用户余额 先比较 再预约
	const sereviceInfo = await productService.findByPk(body.service_id) //产品详情
	// console.log('预约产品详情',sereviceInfo)
	const userInfo = await UserInfo.findOne({where:{user_id:ctx.state.user_id},attributes:['user_info_id','user_flag','vip_remaining_balance','vip_remaining_count']}) // 用户信息
	// console.log('预约产品的用户',userInfo)
	const addReservation = await reservation.create({
		client_id:ctx.state.user_id,
		merchant_id:body.merchant_id,
		reservation_day:body.reservation_day,
		reservation_start_date:body.reservation_start_date,
		reservation_ent_date:body.reservation_ent_date,
		service_id:body.service_id,
		consumption:body.consumption,
		reservation_state:'1',
		pay_state:sereviceInfo.dataValues.is_shop_vip==0?2:1
	})
	let userInfoUpdate = null
	console.log(addReservation.dataValues,sereviceInfo.dataValues,userInfo.dataValues,userInfo.dataValues,ctx.state.user_id,'新增预约')
	if(addReservation.dataValues.Id && sereviceInfo.dataValues.Id && userInfo.dataValues.user_info_id && userInfo.dataValues.user_flag==2){
		console.log(body.consumption,sereviceInfo.dataValues.is_shop_vip,userInfo.dataValues,'判断条件')
		// 如果产品服务支持次卡 如果用户是普通用户 用户预约也是用的次卡 且用户余额次卡够 
		if(body.consumption==1 && sereviceInfo.dataValues.is_shop_vip==1 && userInfo.dataValues.vip_remaining_count>0){ 
			userInfoUpdate = await UserInfo.decrement({
					vip_remaining_count:1
			},{
				where:{
					user_id:ctx.state.user_id
				}
			})
		if(body.consumption==2 && sereviceInfo.dataValues.is_shop_vip==2 && userInfo.dataValues.vip_remaining_balance>=productService.service_price){
			userInfoUpdate = await UserInfo.decrement({
				vip_remaining_balance:productService.service_price
			},{
				where:{
					user_id:ctx.state.user_id
				}
			})
		}
	}
}
	ctx.body = {code:200,msg:'成功',data:null}
}

const getReservation = async (ctx,next)=>{
	// console.log('获取预约列表',ctx.query)
	const body = ctx.query
	let params = null
	if(body.reservation_day){
		params = {merchant_id:body.merchant_id,reservation_day:body.reservation_day}
	}else{
		const today = new Date().toISOString().split('T')[0];
		params = {merchant_id:body.merchant_id, reservation_day: {[Op.gte]: today}}
	}
	const res = await reservation.findAll({
		where:params
	})
	// console.log(res,'预约列表')
	for(let i=0;i<res.length;i++){
		const reservation_name = await User.findByPk(res[i].client_id)
		res[i].dataValues.user_name = reservation_name.user_name
		const sereviceInfo = await productService.findByPk(res[i].service_id)
		res[i].dataValues.service_name = sereviceInfo.service_name
		// console.log(res[i],'看看到底是个什么鬼')
	}
	ctx.body = {code:200,data:res,msg:'成功'}
}

module.exports = {
	addReservation,
	getReservation
}